package zuo.biao.library.ui;

import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import zuo.biao.library.ResourceTable;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.TimeUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 时间选择器
 */
public class TimePickWindow {

    /**
     * mini
     */
    public static final int MIN_LENGHT = 2;

    Context mContext;
    PopupDialog popupDialog;
    String oneSelectStr;
    String towSelectStr;
    String threeSelectStr;
    Text oneShow;
    Text towShow;
    Text threeShow;
    Builder builder;
    Picker pickerOne;
    Picker pickerTow;
    Picker pickerThree;

    String[] years;
    String[] months;
    String[] days;
    private Button btnCancel;
    private Button btnSure;
    private Component component;

    /**启动这个Activity的Intent
     * @param context 上下文
     * @return Intent
     */
    public static Intent createIntent(Context context,OnSureSelectListener sureSelect) {
        return createIntent(context, sureSelect);
    }
    /**启动这个Activity的Intent
     * @param context 上下文
     * @param limitTimeDetail
     * @return
     */
    public static Intent createIntent(Context context, int[] limitTimeDetail,OnSureSelectListener sureSelect) {
        return createIntent(context, limitTimeDetail, sureSelect);
    }
    /**启动这个Activity的Intent
     * @param context 上下文
     * @param limitTimeDetail 限制时间
     * @param defaultTimeDetail 默认
     * @return Intent
     */
    public static Intent createIntent(Context context, int[] limitTimeDetail, int[] defaultTimeDetail,OnSureSelectListener sureSelect) {
        int[] minTimeDetail = null;
        int[] maxTimeDetail = null;
        if (limitTimeDetail != null && limitTimeDetail.length >= MIN_LENGHT) {
            minTimeDetail = TimeUtil.getTimeDetail(System.currentTimeMillis());//基本只会选后面的时间
            maxTimeDetail = limitTimeDetail;
        }
        return createIntent(context, minTimeDetail, maxTimeDetail, defaultTimeDetail,sureSelect);
    }
    /**启动这个Activity的Intent
     * @param context 上下文
     * @param minTimeDetail 最小时间
     * @param maxTimeDetail 最大时间
     * @return  Intent
     */
    public static Intent createIntent(Context context, int[] minTimeDetail, int[] maxTimeDetail, int[] defaultTimeDetail,OnSureSelectListener sureSelect) {
        new TimePickWindow.Builder(context).setSelectListener(sureSelect).show();
        return new Intent();
    }

    public TimePickWindow(Builder builder) {
        this.builder = builder;
        this.mContext = builder.context;
        this.years = builder.years;
        this.months = builder.months;
        this.days = builder.days;
        init();
    }

    /**
     * 初始化
     *
     * @return r
     */
    private TimePickWindow init() {
        component =
                LayoutScatter.getInstance(mContext)
                        .parse(ResourceTable.Layout_ui_layout_pick_time, new DirectionalLayout(mContext), true);

        initView();
        initData();
        initListener();

        popupDialog =
                new PopupDialog(
                        mContext,
                        component,
                        ComponentContainer.LayoutConfig.MATCH_PARENT,
                        ComponentContainer.LayoutConfig.MATCH_CONTENT);
        popupDialog.setAlignment(LayoutAlignment.BOTTOM);
        popupDialog.setCustomComponent(component);
        popupDialog.setAutoClosable(false);

        return this;
    }

    private void initView() {
        oneShow = (Text) component.findComponentById(ResourceTable.Id_txt_one_show);
        towShow = (Text) component.findComponentById(ResourceTable.Id_txt_tow_show);
        threeShow = (Text) component.findComponentById(ResourceTable.Id_txt_three_show);
        pickerOne = (Picker) component.findComponentById(ResourceTable.Id_picker_one);
        pickerTow = (Picker) component.findComponentById(ResourceTable.Id_picker_tow);
        pickerThree = (Picker) component.findComponentById(ResourceTable.Id_picker_three);
        btnCancel = (Button) component.findComponentById(ResourceTable.Id_btn_cancel);
        btnSure = (Button) component.findComponentById(ResourceTable.Id_btn_sure);

        ShapeElement shape = new ShapeElement();
        shape.setShape(ShapeElement.RECTANGLE);
        shape.setRgbColor(RgbColor.fromArgbInt(0xFFEEEEEE));
        pickerOne.setDisplayedLinesElements(shape, shape);
        pickerTow.setDisplayedLinesElements(shape, shape);
        pickerThree.setDisplayedLinesElements(shape, shape);

        pickerOne.setMaxValue(15);
        pickerTow.setMaxValue(12);
        pickerThree.setMaxValue(31);

        pickerOne.setWheelModeEnabled(true);
        pickerTow.setWheelModeEnabled(false);
        pickerThree.setWheelModeEnabled(false);
    }

    private void initData() {
        Calendar c1 = Calendar.getInstance();
        // 获得年份
        int year = c1.get(Calendar.YEAR);
        // 获得月份
        int month = c1.get(Calendar.MONTH) + 1;
        int date = c1.get(Calendar.DATE);

        pickerOne.setValue(2);
        pickerOne.setDisplayedData(years);
        oneSelectStr = years[2];
        oneShow.setText(oneSelectStr + "年");

        pickerTow.setDisplayedData(months);
        pickerTow.setValue(month - 1);
        towSelectStr = months[month - 1];
        towShow.setText(towSelectStr + "月");

        Log.info("TimePickWindow", "months:" + this.months.length);

        c1.set(year, month, 0); // 输入类型为int类型

        int dayOfMonth = c1.get(Calendar.DAY_OF_MONTH);

        List<String> dayList = new ArrayList<>();
        for (int i = 0; i < dayOfMonth; i++) {
            dayList.add((i + 1) + "");
        }
        this.days = dayList.toArray(new String[dayList.size()]);

        Log.info("TimePickWindow", "days:" + this.days.length);

        pickerThree.setDisplayedData(this.days);
        pickerThree.setValue(date - 1);
        threeSelectStr = this.days[date - 1];
        threeShow.setText(threeSelectStr + "日");

    }

    private void initListener() {
        pickerOne.setValueChangedListener(
                new Picker.ValueChangedListener() {
                    @Override
                    public void onValueChanged(Picker picker, int i, int i1) {
                        if (years.length <= i1 || i1 < 0) {
                            return;
                        }
                        oneSelectStr = years[i1];

                        setOneText(oneSelectStr);
                    }
                });

        pickerTow.setValueChangedListener(
                new Picker.ValueChangedListener() {
                    @Override
                    public void onValueChanged(Picker picker, int i, int i1) {
                        if (months.length <= i1 || i1 < 0) {
                            return;
                        }

                        towSelectStr = months[i1];
                        setTowText(towSelectStr);
                    }
                });

        pickerThree.setValueChangedListener(
                new Picker.ValueChangedListener() {
                    @Override
                    public void onValueChanged(Picker picker, int i, int i1) {
                        if (TimePickWindow.this.days.length <= i1 || i1 < 0) {
                            return;
                        }
                        threeSelectStr = TimePickWindow.this.days[i1];
                        setThreeText(threeSelectStr);
                    }
                });

        btnSure.setClickedListener(
                new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        builder.sureSelect.select(oneSelectStr, towSelectStr, threeSelectStr);
                        popupDialog.hide();
                        popupDialog.destroy();
                    }
                });
        btnCancel.setClickedListener(
                new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        popupDialog.hide();
                        popupDialog.destroy();
                    }
                });
    }

    /**
     * shaow
     *
     * @return s
     */
    public TimePickWindow show() {
        popupDialog.show();
        return this;
    }

    private void setOneText(String oneSelectStr) {
        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(
                        new Runnable() {
                            @Override
                            public void run() {
                                oneShow.setText(oneSelectStr + "年");
                            }
                        });
    }

    private void setTowText(String towSelectStr) {
        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(
                        new Runnable() {
                            @Override
                            public void run() {
                                towShow.setText(towSelectStr + "月");
                            }
                        });
        setYearMonthDays(oneSelectStr, towSelectStr);
    }

    private void setYearMonthDays(String year, String month) {
        int ye = Integer.parseInt(year);
        int mo = Integer.parseInt(month);

        Calendar ca = Calendar.getInstance();
        ca.set(ye, mo, 0); // 输入类型为int类型

        int dayOfMonth = ca.get(Calendar.DAY_OF_MONTH);

        List<String> daysList = new ArrayList<>();
        for (int i = 0; i < dayOfMonth; i++) {
            daysList.add((i + 1) + "");
        }
        this.days = daysList.toArray(new String[daysList.size()]);

        Log.info("TimePickWindow", "setYearMonthDays:" + this.days.length);

        pickerThree.setDisplayedData(this.days);
    }

    private void setThreeText(String threeSelectStr) {
        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(
                        new Runnable() {
                            @Override
                            public void run() {
                                threeShow.setText(threeSelectStr + "日");
                            }
                        });
    }

    /**
     * builder模式
     */
    public static class Builder {
        Context context;
        String[] years;
        String[] months;
        String[] days;
        OnSureSelectListener sureSelect;

        public Builder(Context context) {
            String[] yearsList = new String[]{"2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027"};
            String[] monthsList = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};

            this.years = yearsList;
            this.months = monthsList;
            this.context = context;
        }

        /**
         * 可设置数据
         *
         * @param years  years
         * @param months months
         * @param days   days
         * @return b
         */
        public TimePickWindow.Builder setData(String[] years, String[] months, String[] days) {
            this.years = years;
            this.months = months;
            this.days = days;
            return this;
        }

        /**
         * 设置监听
         *
         * @param sureSelect s
         * @return b
         */
        public TimePickWindow.Builder setSelectListener(OnSureSelectListener sureSelect) {
            this.sureSelect = sureSelect;
            return this;
        }

        /**
         * 根show
         */
        public void show() {
            new TimePickWindow(this).show();
        }
    }
    /**
     * 确定监听接口
     */
    public interface OnSureSelectListener {
        /**
         * 选择后
         * @param yearSelect 年
         * @param monthSelect 月
         * @param daySelect 日
         */
        void select(String yearSelect, String monthSelect, String daySelect);
    }
}
